package com.kancy.publicapi.aop;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理
 * @author kancy
 * @see 2019-05-27
 */
@Order(Ordered.HIGHEST_PRECEDENCE)
@RestControllerAdvice
@Configuration
@Slf4j
public class GlobalExceptionTranslator {

    /**
     * 全局异常处理
     * @param e
     * @return
     */
    @ExceptionHandler(Throwable.class)
    public ResponseEntity handleException(Throwable e) {
        log.error("GlobalExceptionAspect print Throwable :",e);
        return ResponseEntity.status(HttpStatus.OK).body(
                String.format("unknow error:%s", e.getMessage())
        );
    }

    /**
     * 参数验证异常处理
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        log.debug("GlobalExceptionAspect print MethodArgumentNotValidException :{}" + ex.getMessage());
        return ResponseEntity.status(HttpStatus.OK).body( String.format("param error:%s", errorMessage(ex)));
    }
    private String errorMessage(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder stringBuilder = new StringBuilder();
        // 只返回一个错误
        if (bindingResult.hasErrors()){
            ObjectError firstError = bindingResult.getAllErrors().get(0);
            stringBuilder.append(StringUtils.isEmpty(firstError.getDefaultMessage()) ? "param is invalid" : firstError.getDefaultMessage());
        }
        return stringBuilder.toString();
    }

}
